/**
 * @Copyright:Copyright (c) 1992 - 2016
 * @Company: TengTong
 */

package com.tengtong.duang.db.handler;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.tengtong.duang.commons.base.impl.IntegerRange;
import com.tengtong.duang.commons.collections.ListUtils;
import com.tengtong.duang.commons.utils.PropertyUtils;
import com.tengtong.duang.db.base.QueryHandler;

/**
 * 将 ResultSet 的内容转换成一个 Bean 内容
 * 
 * @author Jai
 *
 */
public class BeanListHandler<T> implements QueryHandler<List<T>>{
	
	private final Class<T> clazz;
	
	public BeanListHandler(Class<T> d){
		this.clazz = d;
	}

	/* (non-Javadoc)
	 * @see com.tengtong.duang.db.base.QueryHandler#processRow(java.sql.ResultSet)
	 */
	@Override
	public List<T> processRow(ResultSet rs) throws SQLException {
		List<T> result = ListUtils.newSimpleList();
		if(rs != null){
			ResultSetMetaData rsmd = rs.getMetaData();
			try{
				while(rs.next()){
					T data = clazz.newInstance();
					IntegerRange.range(1, rsmd.getColumnCount())
					            .forEachException(i->PropertyUtils.setPropertyValue(data, rsmd.getColumnLabel(i), rs.getObject(i)));
					
					result.add(data);
				}
			}catch(Exception e){
				throw new SQLException(e);
			}
		}
		return result;
	}

}
